package daemon

import (
	"bytes"
	"context"
	"fmt"
	"gluenet/modules/manager/apiserver/daemon/guid"
	"gluenet/modules/manager/apiserver/daemon/scheduler"
	"gluenet/pkg/apis"
	"gluenet/pkg/log/v1"
)

type Daemon struct {
	ctx    context.Context
	logger v1.Logger

	//state    *status.Service
	guid     *guid.Service
	schedule *scheduler.Service
}

func NewServices(ctx context.Context) *Daemon {
	return &Daemon{
		ctx: ctx,
	}
}

// Initialize if failed, please logger Fatal
func (r *Daemon) Initialize(logger v1.Logger, ctx *apis.GlueContext) {
	r.logger = logger

	r.guid = guid.NewGuidService(r.ctx)
	r.schedule = scheduler.NewScheduleService(r.ctx)

	go r.guid.Run(v1.NewLogger("glue.server.daemon.guid"), ctx)
	go r.schedule.Run(v1.NewLogger("glue.server.daemon.schedule"), ctx)
}

func (r *Daemon) Close() error {
	errs := new(bytes.Buffer)

	if err := r.guid.Close(); err != nil {
		errs.WriteString(fmt.Sprintf("guid service close %v\n", err))
	}

	if err := r.schedule.Close(); err != nil {
		errs.WriteString(fmt.Sprintf("guid service close %v\n", err))
	}

	if errs.Len() <= 0 {
		return nil
	} else {
		return fmt.Errorf("%v", errs.String())
	}
}
